package com.ychp.user.service.impl;

import com.google.common.base.Throwables;
import com.ychp.common.model.Response;
import com.ychp.redis.dao.JedisTemplate;
import com.ychp.redis.util.SessionUtils;
import com.ychp.user.dao.UserDao;
import com.ychp.user.model.User;
import com.ychp.user.service.UserReadService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.util.Optional;

/**
 * Desc:
 * Author: <a href="ychp@terminus.io">应程鹏</a>
 * Date: 16/11/7
 */
@Slf4j
@Service
public class UserReadServiceImpl implements UserReadService {

    @Autowired
    private JedisTemplate jedisTemplate;

    @Autowired
    private UserDao userDao;

    public Response findBy(final String token) {
        try {
            Long userId = jedisTemplate.excute(new JedisTemplate.JedisAction<Long>() {

                public Long action(Jedis jedis) {
                    String userIdStr = jedis.get(SessionUtils.getSessionKey(token));
                    if(StringUtils.isEmpty(userIdStr)){
                        return null;
                    }
                    return Long.valueOf(userIdStr);
                }
            });
            if(Optional.ofNullable(userId).isPresent()) {
                User user = userDao.selectById(userId);
                return Response.ok(user);
            }

            return Response.ok(null);
        } catch (Exception e){
            log.error("find user by token fail, token:{}, case:{}", token, Throwables.getStackTraceAsString(e));
            return Response.fail("user.findByToken.fail");
        }
    }
}
